<script>
import audioIcon from "./assets/audio.png"
import stopIcon from "./assets/stop.png"
import { getShowImage, randomString, showToast } from "@/utils"
import persistence from "../store/persistence"

let innerAudioContext
export default {
  name: "audio",
  data() {
    return {
      audioIcon,
      stopIcon,
      playing: false,
    }
  },
  props: {
    audioSrc: {
      type: String,
      default: "",
    },
    text: {
      type: String,
      default: "",
    },
  },
  beforeDestroy() {
    innerAudioContext && innerAudioContext.destroy()
    innerAudioContext = null
  },
  methods: {
    init() {
      let that = this
      if (!innerAudioContext) {
        innerAudioContext = uni.createInnerAudioContext()
      }
      //取消绑定先前绑定的事件
      innerAudioContext.offPlay(() => {
        console.log("offPlay")
      })
      innerAudioContext.onPlay(() => {
        console.log("onPlay")
        that.playing = true
      })
      innerAudioContext.onStop(() => {
        console.log("onStop")
        that.playing = false
      })
      innerAudioContext.onEnded(() => {
        console.log("onEnded")
        that.playing = false
      })
      innerAudioContext.onError((error) => {
        // showToast.error("播放失败");
        console.log(error, "播放出错")
        that.playing = false
      })
    },
    play() {
      this.init()
			//有音频链接才允许播放
			if (this.audioSrc) {
				const audioSrc = getShowImage(this.audioSrc)
				console.log(audioSrc, "audioSrc")
				innerAudioContext.src = audioSrc
				innerAudioContext.play()
			}
    },
    stop() {
      innerAudioContext.stop()
    },
  },
}
</script>

<template>
  <view class="component">
    <view class="text">{{ text }}</view>
    <template v-if="audioSrc">
      <image class="icon" :src="audioIcon" v-if="!playing" @click="play"></image>
      <image class="icon" :src="stopIcon" v-else></image>
    </template>
  </view>
</template>

<style scoped lang="scss">
.component {
  display: flex;
  align-items: center;

  .text {
    font-size: 32rpx;
    color: var(--text-color-light);
  }

  .icon {
    width: 60rpx;
    height: 60rpx;
  }
}
</style>
